import datetime
import json
import time
import requests_go as requests
from common.spider_proxy import SpiderProxy
from django.http import HttpResponse
from common import models

spider_proxy = SpiderProxy()

tls = requests.tls_config.TLSConfig()
tls.ja3 = "771,4865-4866-4867-49195-49199-49196-49200-52393-52392-49171-49172-156-157-47-53,16-18-5-27-0-13-11-43-45-35-51-23-10-65281-17513-21,29-23-24,0"
tls.pseudo_header_order = [
    ":method",
    ":authority",
    ":scheme",
    ":path",
]
tls.tls_extensions.cert_compression_algo = ["brotli"]
tls.tls_extensions.supported_signature_algorithms = [
    "ecdsa_secp256r1_sha256",
    "rsa_pss_rsae_sha256",
    "rsa_pkcs1_sha256",
    "ecdsa_secp384r1_sha384",
    "rsa_pss_rsae_sha384",
    "rsa_pkcs1_sha384",
    "rsa_pss_rsae_sha512",
    "rsa_pkcs1_sha512"
]
tls.tls_extensions.supported_versions = [
    "GREASE",
    "1.3",
    "1.2"
]
tls.tls_extensions.psk_key_exchange_modes = [
    "PskModeDHE"
]
tls.tls_extensions.key_share_curves = [
    "GREASE",
    "X25519"
]
tls.http2_settings.settings = {
    "HEADER_TABLE_SIZE": 65536,
    "ENABLE_PUSH": 0,
    "MAX_CONCURRENT_STREAMS": 1000,
    "INITIAL_WINDOW_SIZE": 6291456,
    "MAX_HEADER_LIST_SIZE": 262144
}
tls.http2_settings.settings_order = [
    "HEADER_TABLE_SIZE",
    "ENABLE_PUSH",
    "MAX_CONCURRENT_STREAMS",
    "INITIAL_WINDOW_SIZE",
    "MAX_HEADER_LIST_SIZE"
]
tls.http2_settings.connection_flow = 15663105


def spider_hotel_list(request):
    response = models.Response()
    if request.method == 'POST':
        params = json.loads(request.body.decode())
        page = params.get("page", 1)
        page_size = params.get("pageSize", 10)
        cookie = params.get('cookie', '')
        city_name = params.get('cityName', '')
        province_name = params.get('provinceName', '')
        if len(cookie) == 0:
            response.error(0, 'Cookie内容为空,')
        else:
            proxy_ip = spider_proxy.get_valid_ip("expedia")
            if proxy_ip is None:
                response.error(-1, "Expedia 无法获取代理ip")
            else:
                url = "https://ebooking.elong.com/ebkroom/hotelManage/getShotelInfoBySupplier"
                payload = {
                    'cityName': city_name,
                    'hotelName': "",
                    "provinceName": province_name,
                    'serviceStatus': "",
                    "serviceDefects": False,
                    "isRead": False,
                    "sHotelId": None,
                    'pageNo': page,
                    'pageSize': page_size
                }
                headers = {
                    'accept': 'application/json, text/javascript, */*; q=0.01',
                    'accept-encoding': 'gzip, deflate, br',
                    'accept-language': 'zh-CN,zh;q=0.9',
                    'content-type': 'application/json;charset=UTF-8',
                    'cookie': cookie,
                    'sec-ch-ua': '".Not/A)Brand";v="99", "Google Chrome";v="103", "Chromium";v="103"',
                    'sec-ch-ua-mobile': '?0',
                    'sec-ch-ua-platform': '"Windows"',
                    'sec-fetch-dest': 'empty',
                    'sec-fetch-mode': 'cors',
                    'sec-fetch-site': 'same-origin',
                    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
                }
                proxy_url = "http://{}:{}".format(proxy_ip.get('ip'), proxy_ip.get('port'))
                proxy = {
                    "https": proxy_url,
                    "http": proxy_url,
                }
                data = json.dumps(payload, separators=(',', ':'))
                rsp = requests.post(url, headers=headers, data=data, proxies=proxy)
                if rsp.status_code == 200:
                    try:
                        mt_rsp = rsp.json()
                        response.success('请求成功', mt_rsp)
                    except ValueError:
                        response.error(-1, 'Cookie已过期，请重新登录')
                elif rsp.status_code == 302:
                    response.error(-1, 'Cookie已过期，请重新登录')
                else:
                    response.error(0, '请求艺龙接口失败，Http code = ' + str(rsp.status_code))
    else:
        response.error(0, '不支持的请求方式')
    return HttpResponse(json.dumps(response.to_dict(), ensure_ascii=False), content_type='application/json')


def spider_hotel_room_list(request):
    response = models.Response()
    if request.method == 'POST':
        params = json.loads(request.body.decode())
        hotel_id = params.get("hotelId", None)
        cookie = params.get('cookie', '')
        if len(cookie) == 0:
            response.error(0, 'Cookie内容为空,')
        else:
            if hotel_id is None:
                response.error(0, '酒店ID不允许为空')
            else:
                proxy_ip = spider_proxy.get_valid_ip("expedia")
                if proxy_ip is None:
                    response.error(-1, "Expedia 无法获取代理ip")
                else:
                    if spider_set_current_hotel(hotel_id, cookie, proxy_ip):
                        url = "https://ebooking.elong.com/product/roomPrice/ajaxRoomRateList"
                        payload = {
                            "hotelId": str(hotel_id),
                            "roomType": "",
                            "startDate": time.strftime("%Y-%m-%d"),
                            "endDate": (datetime.datetime.now() + datetime.timedelta(days=6)).strftime('%Y-%m-%d'),
                            "productType": "0",
                            "sdId": -99
                        }
                        headers = {
                            'accept': 'application/json, text/javascript, */*; q=0.01',
                            'accept-encoding': 'gzip, deflate, br',
                            'accept-language': 'zh-CN,zh;q=0.9',
                            'content-type': 'application/json;charset=UTF-8',
                            'cookie': cookie,
                            'sec-ch-ua': '".Not/A)Brand";v="99", "Google Chrome";v="103", "Chromium";v="103"',
                            'sec-ch-ua-mobile': '?0',
                            'sec-ch-ua-platform': '"Windows"',
                            'sec-fetch-dest': 'empty',
                            'sec-fetch-mode': 'cors',
                            'sec-fetch-site': 'same-origin',
                            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
                        }
                        proxy_url = "http://{}:{}".format(proxy_ip.get('ip'), proxy_ip.get('port'))
                        proxy = {
                            "https": proxy_url,
                            "http": proxy_url,
                        }
                        data = json.dumps(payload, separators=(',', ':'))
                        rsp = requests.post(url, headers=headers, data=data, proxies=proxy)
                        if rsp.status_code == 200:
                            try:
                                mt_rsp = rsp.json()
                                response.success('请求成功', mt_rsp)
                            except ValueError:
                                response.error(-1, 'Cookie已过期，请重新登录')
                        elif rsp.status_code == 302:
                            response.error(-1, 'Cookie已过期，请重新登录')
                        else:
                            response.error(0, '请求艺龙接口失败，Http code = ' + str(rsp.status_code))
                    else:
                        response.error(0, '设置当前酒店失败')
    else:
        response.error(0, '不支持的请求方式')
    return HttpResponse(json.dumps(response.to_dict(), ensure_ascii=False), content_type='application/json')


def spider_hotel_sale_room_list(request):
    response = models.Response()
    if request.method == 'POST':
        params = json.loads(request.body.decode())
        hotel_id = params.get("hotelId", None)
        room_id = params.get("roomId", None)
        cookie = params.get('cookie', '')
        if len(cookie) == 0:
            response.error(0, 'Cookie内容为空,')
        else:
            if hotel_id is None:
                response.error(0, '酒店ID不允许为空')
            else:
                proxy_ip = spider_proxy.get_valid_ip("expedia")
                if proxy_ip is None:
                    response.error(-1, "Expedia 无法获取代理ip")
                else:
                    if spider_set_current_hotel(hotel_id, cookie, proxy_ip):
                        url = "https://ebooking.elong.com/product/roomPrice/ajaxRoomRate"
                        payload = {
                            "hotelId": str(hotel_id),
                            "roomType": room_id,
                            "startDate": time.strftime("%Y-%m-%d"),
                            "endDate": (datetime.datetime.now() + datetime.timedelta(days=6)).strftime('%Y-%m-%d'),
                            "productType": "0",
                            "sdId": -99
                        }
                        headers = {
                            'accept': 'application/json, text/javascript, */*; q=0.01',
                            'accept-encoding': 'gzip, deflate, br',
                            'accept-language': 'zh-CN,zh;q=0.9',
                            'content-type': 'application/json;charset=UTF-8',
                            'cookie': cookie,
                            'sec-ch-ua': '".Not/A)Brand";v="99", "Google Chrome";v="103", "Chromium";v="103"',
                            'sec-ch-ua-mobile': '?0',
                            'sec-ch-ua-platform': '"Windows"',
                            'sec-fetch-dest': 'empty',
                            'sec-fetch-mode': 'cors',
                            'sec-fetch-site': 'same-origin',
                            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
                        }
                        proxy_url = "http://{}:{}".format(proxy_ip.get('ip'), proxy_ip.get('port'))
                        proxy = {
                            "https": proxy_url,
                            "http": proxy_url,
                        }
                        data = json.dumps(payload, separators=(',', ':'))
                        rsp = requests.post(url, headers=headers, data=data, proxies=proxy)
                        if rsp.status_code == 200:
                            try:
                                mt_rsp = rsp.json()
                                response.success('请求成功', mt_rsp)
                            except ValueError:
                                response.error(-1, 'Cookie已过期，请重新登录')
                        elif rsp.status_code == 302:
                            response.error(-1, 'Cookie已过期，请重新登录')
                        else:
                            response.error(0, '请求艺龙接口失败，Http code = ' + str(rsp.status_code))
                    else:
                        response.error(0, '设置当前酒店异常')
    else:
        response.error(0, '不支持的请求方式')
    return HttpResponse(json.dumps(response.to_dict(), ensure_ascii=False), content_type='application/json')

def spider_hotel_sale_room_list_2(request):
    response = models.Response()
    if request.method == 'POST':
        params = json.loads(request.body.decode())
        hotel_id = params.get("hotelId", None)
        room_id = params.get("roomId", None)
        room_name = params.get("roomName", None)
        cookie = params.get('cookie', '')
        if len(cookie) == 0:
            response.error(0, 'Cookie内容为空,')
        else:
            if hotel_id is None:
                response.error(0, '酒店ID不允许为空')
            else:
                proxy_ip = spider_proxy.get_valid_ip("expedia")
                if proxy_ip is None:
                    response.error(-1, "Expedia 无法获取代理ip")
                else:
                    if spider_set_current_hotel(hotel_id, cookie, proxy_ip):
                        url = "https://ebooking.elong.com/ebkroom/getProductInfoListAndPrice"
                        payload = {
                            "hotelId": str(hotel_id),
                            "roomType": room_id,
                            "days": 7,
                            "showProductType": 1,
                            "beginDate": time.strftime("%Y-%m-%d"),
                            "endDate": (datetime.datetime.now() + datetime.timedelta(days=6)).strftime('%Y-%m-%d'),
                            "sdId": -99,
                            "roomTypeAndRoomIdInfo": {
                                "roomTypeName": room_name,
                                "roomTypeId": room_id
                            }
                        }
                        headers = {
                            'accept': 'application/json, text/javascript, */*; q=0.01',
                            'accept-encoding': 'gzip, deflate, br',
                            'accept-language': 'zh-CN,zh;q=0.9',
                            'content-type': 'application/json;charset=UTF-8',
                            'cookie': cookie,
                            'sec-ch-ua': '".Not/A)Brand";v="99", "Google Chrome";v="103", "Chromium";v="103"',
                            'sec-ch-ua-mobile': '?0',
                            'sec-ch-ua-platform': '"Windows"',
                            'sec-fetch-dest': 'empty',
                            'sec-fetch-mode': 'cors',
                            'sec-fetch-site': 'same-origin',
                            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
                        }
                        proxy_url = "http://{}:{}".format(proxy_ip.get('ip'), proxy_ip.get('port'))
                        proxy = {
                            "https": proxy_url,
                            "http": proxy_url,
                        }
                        data = json.dumps(payload, separators=(',', ':'))
                        rsp = requests.post(url, headers=headers, data=data,  proxies=proxy)
                        if rsp.status_code == 200:
                            try:
                                mt_rsp = rsp.json()
                                response.success('请求成功', mt_rsp)
                            except ValueError:
                                response.error(-1, 'Cookie已过期，请重新登录')
                        elif rsp.status_code == 302:
                            response.error(-1, 'Cookie已过期，请重新登录')
                        else:
                            response.error(0, '请求艺龙接口失败，Http code = ' + str(rsp.status_code))
                    else:
                        response.error(0, '设置当前酒店异常')
    else:
        response.error(0, '不支持的请求方式')
    return HttpResponse(json.dumps(response.to_dict(), ensure_ascii=False), content_type='application/json')


def spider_hotel_all_room_list(request):
    response = models.Response()
    if request.method == 'POST':
        params = json.loads(request.body.decode())
        hotel_id = params.get("hotelId", None)
        cookie = params.get('cookie', '')
        if len(cookie) == 0:
            response.error(0, 'Cookie内容为空,')
        else:
            if hotel_id is None:
                response.error(0, '酒店ID不允许为空')
            else:
                proxy_ip = spider_proxy.get_valid_ip("expedia")
                if proxy_ip is None:
                    response.error(-1, "Expedia 无法获取代理ip")
                else:
                    url = "https://ebooking.elong.com/ebkroom/hotelManage/getShotelRoomList"
                    payload = {
                        "realRequest": {
                            "scope": 17,
                            "shotelId": str(hotel_id)
                        }
                    }
                    headers = {
                        'accept': 'application/json, text/javascript, */*; q=0.01',
                        'accept-encoding': 'gzip, deflate, br',
                        'accept-language': 'zh-CN,zh;q=0.9',
                        'content-type': 'application/json;charset=UTF-8',
                        'cookie': cookie,
                        'sec-ch-ua': '".Not/A)Brand";v="99", "Google Chrome";v="103", "Chromium";v="103"',
                        'sec-ch-ua-mobile': '?0',
                        'sec-ch-ua-platform': '"Windows"',
                        'sec-fetch-dest': 'empty',
                        'sec-fetch-mode': 'cors',
                        'sec-fetch-site': 'same-origin',
                        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
                    }
                    proxy_url = "http://{}:{}".format(proxy_ip.get('ip'), proxy_ip.get('port'))
                    proxy = {
                        "https": proxy_url,
                        "http": proxy_url,
                    }
                    data = json.dumps(payload, separators=(',', ':'))
                    rsp = requests.post(url, headers=headers, data=data, proxies=proxy)
                    if rsp.status_code == 200:
                        try:
                            mt_rsp = rsp.json()
                            response.success('请求成功', mt_rsp)
                        except ValueError:
                            response.error(-1, 'Cookie已过期，请重新登录')
                    elif rsp.status_code == 302:
                        response.error(-1, 'Cookie已过期，请重新登录')
                    else:
                        response.error(0, '请求艺龙接口失败，Http code = ' + str(rsp.status_code))
    else:
        response.error(0, '不支持的请求方式')
    return HttpResponse(json.dumps(response.to_dict(), ensure_ascii=False), content_type='application/json')


def spider_hotel_all_sale_room_list(request):
    response = models.Response()
    if request.method == 'POST':
        params = json.loads(request.body.decode())
        hotel_id = params.get("hotelId", None)
        page = params.get("page", None)
        page_size = params.get("pageSize", None)
        cookie = params.get('cookie', '')
        if len(cookie) == 0:
            response.error(0, 'Cookie内容为空,')
        else:
            if hotel_id is None:
                response.error(0, '酒店ID不允许为空')
            else:
                proxy_ip = spider_proxy.get_valid_ip("expedia")
                if proxy_ip is None:
                    response.error(-1, "Expedia 无法获取代理ip")
                else:
                    url = "https://ebooking.elong.com/ebkroom/hotelManage/getRpInfolist"
                    payload = {
                        "pageNo": page,
                        "pageSize": page_size,
                        "shotelId": str(hotel_id),
                        "from": "hotelManage",
                        "isHour": None,
                        "sroomIds": [],
                        "breakfastFlag": None
                    }

                    params = {
                        'url': url,
                        'payload': json.dumps(payload, separators=(",", ":"))
                    }
                    rsp = requests.post("http://sign.silvtravel.com/elong", data=params).json()
                    user_dun = rsp.get('value', None)
                    if user_dun is not None:
                        headers = {
                            "accept": "application/json, text/plain, */*",
                            "accept-language": "zh-CN,zh;q=0.9",
                            "content-type": "application/json",
                            "origin": "https://ebooking.elong.com",
                            "priority": "u=1, i",
                            "referer": "https://ebooking.elong.com/ebkcommon/dashboard",
                            "sec-ch-ua": "\"Chromium\";v=\"124\", \"Google Chrome\";v=\"124\", \"Not-A.Brand\";v=\"99\"",
                            "sec-ch-ua-mobile": "?0",
                            "sec-ch-ua-platform": "\"Windows\"",
                            "sec-fetch-dest": "empty",
                            "sec-fetch-mode": "cors",
                            'cookie': cookie,
                            "user-dun": user_dun,
                            "sec-fetch-site": "same-origin",
                            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
                        }
                        proxy_url = "http://{}:{}".format(proxy_ip.get('ip'), proxy_ip.get('port'))
                        proxy = {
                            "https": proxy_url,
                            "http": proxy_url,
                        }
                        data = json.dumps(payload, separators=(',', ':'))
                        rsp = requests.post(url, headers=headers, data=data, proxies=proxy)
                        if rsp.status_code == 200:
                            try:
                                mt_rsp = rsp.json()
                                response.success('请求成功', mt_rsp)
                            except ValueError:
                                response.error(-1, 'Cookie已过期，请重新登录')
                        elif rsp.status_code == 302:
                            response.error(-1, 'Cookie已过期，请重新登录')
                        else:
                            response.error(0, '请求艺龙接口失败，Http code = ' + str(rsp.status_code))
                    else:
                        response.error(0, '请求艺龙接口失败，获取加密校验参数失败')
    else:
        response.error(0, '不支持的请求方式')
    return HttpResponse(json.dumps(response.to_dict(), ensure_ascii=False), content_type='application/json')

def spider_batch_update_sale_room_info(request):
    response = models.Response()
    if request.method == 'POST':
        params = json.loads(request.body.decode())
        hotel_id = params.get("hotelId", None)
        content = params.get("content", None)
        cookie = params.get('cookie', '')
        if len(cookie) == 0:
            response.error(0, 'Cookie内容为空,')
        elif content is None:
            response.error(0, '修改内容不允许为空')
        else:
            if hotel_id is None:
                response.error(0, '酒店ID不允许为空')
            else:
                url = "https://ebooking.elong.com/ebkroom/hotelManage/saveRPInfoProductPOST"
                headers = {
                    "accept": "application/json, text/plain, */*",
                    "accept-language": "zh-CN,zh;q=0.9",
                    "content-type": "application/json",
                    "origin": "https://ebooking.elong.com",
                    "priority": "u=1, i",
                    "referer": "https://ebooking.elong.com/ebkcommon/dashboard",
                    "sec-ch-ua": "\"Chromium\";v=\"124\", \"Google Chrome\";v=\"124\", \"Not-A.Brand\";v=\"99\"",
                    "sec-ch-ua-mobile": "?0",
                    "sec-ch-ua-platform": "\"Windows\"",
                    "sec-fetch-dest": "empty",
                    "sec-fetch-mode": "cors",
                    'cookie': cookie,
                    "sec-fetch-site": "same-origin",
                    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
                }
                data = json.dumps(content, separators=(',', ':'))
                rsp = requests.post(url, headers=headers, data=data)
                if rsp.status_code == 200:
                    try:
                        mt_rsp = rsp.json()
                        response.success('请求成功', mt_rsp)
                    except ValueError:
                        response.error(-1, 'Cookie已过期，请重新登录')
                elif rsp.status_code == 302:
                    response.error(-1, 'Cookie已过期，请重新登录')
                else:
                    response.error(0, '请求艺龙接口失败，Http code = ' + str(rsp.status_code))
    else:
        response.error(0, '不支持的请求方式')
    return HttpResponse(json.dumps(response.to_dict(), ensure_ascii=False), content_type='application/json')


def spider_update_price(request):
    response = models.Response()
    if request.method == 'POST':
        params = json.loads(request.body.decode('utf-8'))
        price_info = params.get('priceInfo', None)
        hotel_id = params.get("hotelId", None)
        cookie = params.get('cookie', '')
        if len(cookie) == 0:
            response.error(0, 'Cookie内容为空,')
        elif price_info is None:
            response.error(0, '价格参数不允许为空')
        elif hotel_id is None:
            response.error(0, '酒店ID不允许为空')
        else:
            proxy_ip = spider_proxy.get_valid_ip("expedia")
            if proxy_ip is None:
                response.error(-1, "Expedia 无法获取代理ip")
            else:
                if spider_set_current_hotel(hotel_id, cookie, proxy_ip):
                    url = "https://ebooking.elong.com/product/roomPrice/ajaxSavePrice"
                    headers = {
                        'accept': 'application/json, text/javascript, */*; q=0.01',
                        'accept-encoding': 'gzip, deflate, br',
                        'accept-language': 'zh-CN,zh;q=0.9',
                        'content-type': 'application/json;charset=UTF-8',
                        'cookie': cookie,
                        'sec-ch-ua': '".Not/A)Brand";v="99", "Google Chrome";v="103", "Chromium";v="103"',
                        'sec-ch-ua-mobile': '?0',
                        'sec-ch-ua-platform': '"Windows"',
                        'sec-fetch-dest': 'empty',
                        'sec-fetch-mode': 'cors',
                        'sec-fetch-site': 'same-origin',
                        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
                    }
                    proxy_url = "http://{}:{}".format(proxy_ip.get('ip'), proxy_ip.get('port'))
                    proxy = {
                        "https": proxy_url,
                        "http": proxy_url,
                    }
                    data = json.dumps(price_info, separators=(',', ':'))
                    rsp = requests.post(url, headers=headers, data=data, proxies=proxy)
                    if rsp.status_code == 200:
                        try:
                            mt_rsp = rsp.json()
                            response.success('请求成功', mt_rsp)
                        except ValueError:
                            response.error(-1, 'Cookie已过期，请重新登录')
                    elif rsp.status_code == 302:
                        response.error(-1, 'Cookie已过期，请重新登录')
                    else:
                        response.error(0, '请求美团接口失败，Http code = ' + str(rsp.status_code))
                else:
                    response.error(0, '设置当前酒店异常')
    else:
        response.error(0, '不支持的请求方式')
    return HttpResponse(json.dumps(response.to_dict(), ensure_ascii=False), content_type='application/json')


# 房型批量上下线
def spider_batch_onoff_room(request):
    response = models.Response()
    if request.method == 'POST':
        params = json.loads(request.body.decode('utf-8'))
        room_status = params.get("roomStatus", None)
        hotel_id = params.get("hotelId", None)
        cookie = params.get('cookie', '')
        if len(cookie) == 0:
            response.error(0, 'Cookie内容为空,')
        elif room_status is None:
            response.error(0, '房态参数不允许为空')
        else:
            proxy_ip = spider_proxy.get_valid_ip("expedia")
            if proxy_ip is None:
                response.error(-1, "Expedia 无法获取代理ip")
            else:
                url = "https://ebooking.elong.com/ebkroom/hotelManage/updatesRoomStatus"
                headers = {
                    'accept': 'application/json, text/javascript, */*; q=0.01',
                    'accept-encoding': 'gzip, deflate, br',
                    'accept-language': 'zh-CN,zh;q=0.9',
                    'content-type': 'application/json;charset=UTF-8',
                    'cookie': cookie,
                    'sec-ch-ua': '".Not/A)Brand";v="99", "Google Chrome";v="103", "Chromium";v="103"',
                    'sec-ch-ua-mobile': '?0',
                    'sec-ch-ua-platform': '"Windows"',
                    'sec-fetch-dest': 'empty',
                    'sec-fetch-mode': 'cors',
                    'sec-fetch-site': 'same-origin',
                    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
                }
                proxy_url = "http://{}:{}".format(proxy_ip.get('ip'), proxy_ip.get('port'))
                proxy = {
                    "https": proxy_url,
                    "http": proxy_url,
                }
                data = json.dumps(room_status, separators=(',', ':'))
                rsp = requests.post(url, headers=headers, data=data, proxies=proxy)
                if rsp.status_code == 200:
                    try:
                        mt_rsp = rsp.json()
                        response.success('请求成功', mt_rsp)
                    except ValueError:
                        response.error(-1, 'Cookie已过期，请重新登录')
                elif rsp.status_code == 302:
                    response.error(-1, 'Cookie已过期，请重新登录')
                else:
                    response.error(0, '请求艺龙接口失败，Http code = ' + str(rsp.status_code))
    else:
        response.error(0, '不支持的请求方式')
    return HttpResponse(json.dumps(response.to_dict(), ensure_ascii=False), content_type='application/json')


def spider_update_room_status(request):
    response = models.Response()
    if request.method == 'POST':
        params = json.loads(request.body.decode('utf-8'))
        room_status = params.get("roomStatus", None)
        hotel_id = params.get("hotelId", None)
        cookie = params.get('cookie', '')
        if len(cookie) == 0:
            response.error(0, 'Cookie内容为空,')
        elif room_status is None:
            response.error(0, '房态参数不允许为空')
        elif hotel_id is None:
            response.error(0, '酒店ID不允许为空')
        else:
            proxy_ip = spider_proxy.get_valid_ip("expedia")
            if proxy_ip is None:
                response.error(-1, "Expedia 无法获取代理ip")
            else:
                if spider_set_current_hotel(hotel_id, cookie, proxy_ip):
                    url = "https://ebooking.elong.com/ebkroom/roomOperate/batchEditRoomStatus"
                    headers = {
                        'accept': 'application/json, text/javascript, */*; q=0.01',
                        'accept-encoding': 'gzip, deflate, br',
                        'accept-language': 'zh-CN,zh;q=0.9',
                        'content-type': 'application/json;charset=UTF-8',
                        'cookie': cookie,
                        'sec-ch-ua': '".Not/A)Brand";v="99", "Google Chrome";v="103", "Chromium";v="103"',
                        'sec-ch-ua-mobile': '?0',
                        'sec-ch-ua-platform': '"Windows"',
                        'sec-fetch-dest': 'empty',
                        'sec-fetch-mode': 'cors',
                        'sec-fetch-site': 'same-origin',
                        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
                    }
                    proxy_url = "http://{}:{}".format(proxy_ip.get('ip'), proxy_ip.get('port'))
                    proxy = {
                        "https": proxy_url,
                        "http": proxy_url,
                    }
                    data = json.dumps(room_status, separators=(',', ':'))
                    rsp = requests.post(url, headers=headers, data=data, proxies=proxy)
                    if rsp.status_code == 200:
                        try:
                            mt_rsp = rsp.json()
                            response.success('请求成功', mt_rsp)
                        except ValueError:
                            response.error(-1, 'Cookie已过期，请重新登录')
                    elif rsp.status_code == 302:
                        response.error(-1, 'Cookie已过期，请重新登录')
                    else:
                        response.error(0, '请求艺龙接口失败，Http code = ' + str(rsp.status_code))
                else:
                    response.error(0, '设置当前酒店异常')
    else:
        response.error(0, '不支持的请求方式')
    return HttpResponse(json.dumps(response.to_dict(), ensure_ascii=False), content_type='application/json')


def spider_update_saleroom_status(request):
    response = models.Response()
    if request.method == 'POST':
        params = json.loads(request.body.decode('utf-8'))
        room_status = params.get("roomStatus", None)
        hotel_id = params.get("hotelId", None)
        cookie = params.get('cookie', '')
        if len(cookie) == 0:
            response.error(0, 'Cookie内容为空,')
        elif room_status is None:
            response.error(0, '房态参数不允许为空')
        elif hotel_id is None:
            response.error(0, '酒店ID不允许为空')
        else:
            proxy_ip = spider_proxy.get_valid_ip("expedia")
            if proxy_ip is None:
                response.error(-1, "Expedia 无法获取代理ip")
            else:
                if spider_set_current_hotel(hotel_id, cookie, proxy_ip):
                    url = "https://ebooking.elong.com/ebkroom/roomOperate/setPriceStatus"
                    headers = {
                        'accept': 'application/json, text/javascript, */*; q=0.01',
                        'accept-encoding': 'gzip, deflate, br',
                        'accept-language': 'zh-CN,zh;q=0.9',
                        'content-type': 'application/json;charset=UTF-8',
                        'cookie': cookie,
                        'sec-ch-ua': '".Not/A)Brand";v="99", "Google Chrome";v="103", "Chromium";v="103"',
                        'sec-ch-ua-mobile': '?0',
                        'sec-ch-ua-platform': '"Windows"',
                        'sec-fetch-dest': 'empty',
                        'sec-fetch-mode': 'cors',
                        'sec-fetch-site': 'same-origin',
                        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
                    }
                    proxy_url = "http://{}:{}".format(proxy_ip.get('ip'), proxy_ip.get('port'))
                    proxy = {
                        "https": proxy_url,
                        "http": proxy_url,
                    }
                    data = json.dumps(room_status, separators=(',', ':'))
                    rsp = requests.post(url, headers=headers, data=data, proxies=proxy)
                    if rsp.status_code == 200:
                        try:
                            mt_rsp = rsp.json()
                            response.success('请求成功', mt_rsp)
                        except ValueError:
                            response.error(-1, 'Cookie已过期，请重新登录')
                    elif rsp.status_code == 302:
                        response.error(-1, 'Cookie已过期，请重新登录')
                    else:
                        response.error(0, '请求艺龙接口失败，Http code = ' + str(rsp.status_code))
                else:
                    response.error(0, '设置当前酒店异常')
    else:
        response.error(0, '不支持的请求方式')
    return HttpResponse(json.dumps(response.to_dict(), ensure_ascii=False), content_type='application/json')


def spider_get_room_status(request):
    response = models.Response()
    if request.method == 'POST':
        params = json.loads(request.body.decode('utf-8'))
        hotel_id = params.get("hotelId", None)
        begin_date = params.get("beginDate", None)
        day = params.get("day", None)
        cookie = params.get('cookie', '')
        if len(cookie) == 0:
            response.error(0, 'Cookie内容为空,')
        elif begin_date is None:
            response.error(0, '开始日期不允许为空')
        elif day is None:
            response.error(0, '天数不允许为空')
        elif hotel_id is None:
            response.error(0, '酒店ID不允许为空')
        else:
            proxy_ip = spider_proxy.get_valid_ip("expedia")
            if proxy_ip is None:
                response.error(-1, "Expedia 无法获取代理ip")
            else:
                if spider_set_current_hotel(hotel_id, cookie, proxy_ip):
                    url = "https://ebooking.elong.com/ebkroom/getInventoryDetail"
                    payload = {
                        'beginDate': begin_date,
                        'day': day
                    }
                    params = {
                        'url': url,
                        'payload': json.dumps(payload, separators=(",", ":"))
                    }
                    rsp = requests.post("http://sign.silvtravel.com/elong", data=params).json()
                    user_dun = rsp.get('value', None)
                    if user_dun is not None:
                        headers = {
                            'accept': 'application/json, text/javascript, */*; q=0.01',
                            'accept-encoding': 'gzip, deflate, br',
                            'accept-language': 'zh-CN,zh;q=0.9',
                            'content-type': 'application/json;charset=UTF-8',
                            'cookie': cookie,
                            'sec-ch-ua': '".Not/A)Brand";v="99", "Google Chrome";v="103", "Chromium";v="103"',
                            'sec-ch-ua-mobile': '?0',
                            'sec-ch-ua-platform': '"Windows"',
                            'sec-fetch-dest': 'empty',
                            'sec-fetch-mode': 'cors',
                            'sec-fetch-site': 'same-origin',
                            "user-dun": user_dun,
                            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
                        }
                        proxy_url = "http://{}:{}".format(proxy_ip.get('ip'), proxy_ip.get('port'))
                        proxy = {
                            "https": proxy_url,
                            "http": proxy_url,
                        }
                        data = json.dumps(payload, separators=(',', ':'))
                        rsp = requests.post(url, headers=headers, data=data, proxies=proxy)
                        if rsp.status_code == 200:
                            try:
                                mt_rsp = rsp.json()
                                response.success('请求成功', mt_rsp)
                            except ValueError:
                                response.error(-1, 'Cookie已过期，请重新登录')
                        elif rsp.status_code == 302:
                            response.error(-1, 'Cookie已过期，请重新登录')
                        else:
                            response.error(0, '请求艺龙接口失败，Http code = ' + str(rsp.status_code))
                    else:
                        response.error(0, '请求艺龙接口失败，获取加密校验参数失败')
                else:
                    response.error(0, '设置当前酒店异常')
    else:
        response.error(0, '不支持的请求方式')
    return HttpResponse(json.dumps(response.to_dict(), ensure_ascii=False), content_type='application/json')


def spider_set_current_hotel(hotel_id, cookie, proxy_ip):
    url = "https://ebooking.elong.com/ebkcommon/currentHotel/setCurrentHotel"
    payload = {
        "hotelId": str(hotel_id)
    }

    data = {
        'url': url,
        'payload': json.dumps(payload, separators=(",", ":"))
    }

    rsp = requests.post("http://sign.silvtravel.com/elong", data=data).json()
    user_dun = rsp.get('value', None)
    if user_dun is not None:
        headers = {
            'accept': 'application/json, text/javascript, */*; q=0.01',
            'accept-encoding': 'gzip, deflate, br',
            'accept-language': 'zh-CN,zh;q=0.9',
            'content-type': 'application/json;charset=UTF-8',
            'cookie': cookie,
            'sec-ch-ua': '".Not/A)Brand";v="99", "Google Chrome";v="103", "Chromium";v="103"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            "user-dun": user_dun,
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
        }
        proxy_url = "http://{}:{}".format(proxy_ip.get('ip'), proxy_ip.get('port'))
        proxy = {
            "https": proxy_url,
            "http": proxy_url,
        }
        data = json.dumps(payload, separators=(',', ':'))
        rsp = requests.post(url, headers=headers, data=data, proxies=proxy)
        if rsp.status_code == 200:
            return True
        else:
            return False
    else:
        return False


def spider_get_order_list(request):
    response = models.Response()
    if request.method == 'POST':
        params = json.loads(request.body.decode('utf-8'))
        order_id = params.get('orderId', None)
        start_date = params.get('startDate', None)
        end_date = params.get('endDate', None)
        page = params.get('page', None)
        page_size = params.get("pageSize", None)
        cookie = params.get('cookie', '')
        if len(cookie) == 0:
            response.error(0, 'Cookie内容为空,')
        elif start_date is None or end_date is None:
            response.error(0, '开始/结束时间不允许为空')
        else:
            url = "https://ebooking.elong.com/ebkorder/searchOrder/getSearchOrders"
            payload = {"orderId": order_id, "confirmNo": "", "guestName": "", "statusType": 0, "dateSearchType": 0,
                       "confirmType": 0, "beginDate": start_date, "endDate": end_date, "paymentType": 0,
                       "guaranteeType": 0,
                       "provinceId": "", "filterHotelId": "", "roomTypeId": None, "roomNo": None, "otaType": 0,
                       "sdId": -99, "filterAutoConfirmOrder": False, "pageNum": page, "pageSize": page_size}
            headers = {
                'accept': 'application/json, text/javascript, */*; q=0.01',
                'accept-encoding': 'gzip, deflate, br',
                'accept-language': 'zh-CN,zh;q=0.9',
                'content-type': 'application/json;charset=UTF-8',
                'cookie': cookie,
                'sec-ch-ua': '".Not/A)Brand";v="99", "Google Chrome";v="103", "Chromium";v="103"',
                'sec-ch-ua-mobile': '?0',
                'sec-ch-ua-platform': '"Windows"',
                'sec-fetch-dest': 'empty',
                'sec-fetch-mode': 'cors',
                'sec-fetch-site': 'same-origin',
                'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
            }
            data = json.dumps(payload, separators=(',', ':'))
            rsp = requests.post(url, headers=headers, data=data)
            if rsp.status_code == 200:
                try:
                    mt_rsp = rsp.json()
                    response.success('请求成功', mt_rsp)
                except ValueError:
                    response.error(-1, 'Cookie已过期，请重新登录')
            elif rsp.status_code == 302:
                response.error(-1, 'Cookie已过期，请重新登录')
            else:
                response.error(0, '请求艺龙接口失败，Http code = ' + str(rsp.status_code))
    else:
        response.error(0, '不支持的请求方式')
    return HttpResponse(json.dumps(response.to_dict(), ensure_ascii=False), content_type='application/json')
